<template>
  <div class="wordSystem">
    <Button @click="handleDownLoad">下载</Button>
  </div>
</template>
<script>
import { getWord } from "@/api/upload.js";
import Docxtemplater from "docxtemplater";
import PizZip from "pizzip";
import PizZipUtils from "pizzip/utils";

export default {
  data() {
    return {
      html: "<div>hello world</div>",
      documentData: null,
    };
  },
  methods: {
    async handleDownLoad() {
      //   getWord().then((response) => {
      //     // 创建一个URL对象并用于创建一个临时的a标签来模拟点击下载
      //     const url = window.URL.createObjectURL(
      //       new Blob([response], { type: "application/x-msdownload" })
      //     );
      //     const link = document.createElement("a");
      //     link.href = url;
      //     link.setAttribute("download", "document.docx"); // 或者从响应头中获取文件名
      //     document.body.appendChild(link);
      //     link.click();
      //     link.remove(); // 完成后移除临时创建的链接
      //     window.URL.revokeObjectURL(url); // 释放URL对象
      //   });
      let response = await fetch("/static/tpl.docx");
      console.log("_response_", response);
      let templateData = await response.arrayBuffer();
      console.log("_ templateData _", templateData);
      // 将 ArrayBuffer 转换为 Uint8Array
      let uint8Array = new Uint8Array(templateData);
      console.log("_ uint8Array _", uint8Array);

      // 创建一个 Docxtemplater 实例并加载 Zip
      let doc = new Docxtemplater();
      let zip = new PizZip(uint8Array);

      doc.loadZip(zip);
      // 设置要替换的数据
      let data = {
        name: "小明",
        time:"2020-01-02"
      };

      doc.setData(data);

      // 渲染文档
      doc.render();

      // 获取渲染后的 Blob
      let updatedBlob = doc.getZip().generate({
        type: "blob",
        mimeType:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      });
      // 创建一个 URL，用于下载最终文档
      let updatedUrl = URL.createObjectURL(updatedBlob);

      // 创建一个 <a> 标签来触发下载
      let link = document.createElement("a");
      link.href = updatedUrl;
      link.download = "updated_document.docx";
      link.click();

      // 释放 URL 对象
      URL.revokeObjectURL(updatedUrl);
    },
  },
};
</script>
